package com.chen.project.white_jotter.config;


import com.chen.project.white_jotter.utils.JWTUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT验证过滤器
 */
@Component
public class JWTAuthorizationTokenFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;
    private final JWTUtil JWTUtil;
    private final String tokenHeader;


    /**
     * 构造器
     * @param userDetailsService
     * @param JWTUtil
     * @param tokenHeader
     */
    public JWTAuthorizationTokenFilter(@Qualifier("userDetailsService") UserDetailsService userDetailsService,
                                       JWTUtil JWTUtil, @Value("${jwt.token}") String tokenHeader) {
        this.userDetailsService = userDetailsService;
        this.JWTUtil = JWTUtil;
        this.tokenHeader = tokenHeader;
    }

    /**
     * 验证请求中的 jwt
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        final String requestHeader = request.getHeader(this.tokenHeader);
        String username = null;
        String authToken = null;

        // 如果是登陆请求就不必携带 jwt
        String requestURI = request.getRequestURI();
        if("/api/login".equals(requestURI) || "/api/register".equals(requestURI)){
            chain.doFilter(request, response);
            return;
        }

        // 判断请求头是否带有 jwt，从中解析出用户名
        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
            authToken = requestHeader.substring(7);
            try {
                username = JWTUtil.getUsernameFromToken(authToken);
            } catch (ExpiredJwtException e) {
                // e.printStackTrace();
            }
        }

        // 如果jwt为真
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (JWTUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }
}

